import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Category, Difficulty } from "@/types/question";

interface AppSettings {
  darkMode: boolean;
  simulationDuration: number; // in minutes
  simulationQuestionsCount: number;
  notificationsEnabled: boolean;
  selectedCategories: Category[];
  selectedDifficulties: Difficulty[];
}

interface AppState extends AppSettings {
  setDarkMode: (enabled: boolean) => void;
  setSimulationDuration: (minutes: number) => void;
  setSimulationQuestionsCount: (count: number) => void;
  setNotificationsEnabled: (enabled: boolean) => void;
  toggleCategory: (category: Category) => void;
  toggleDifficulty: (difficulty: Difficulty) => void;
  resetSettings: () => void;
}

const initialSettings: AppSettings = {
  darkMode: true,
  simulationDuration: 30, // 30 minutes
  simulationQuestionsCount: 5,
  notificationsEnabled: true,
  selectedCategories: [],
  selectedDifficulties: ["easy", "medium"],
};

export const useAppStore = create<AppState>()(
  persist(
    (set) => ({
      ...initialSettings,
      setDarkMode: (enabled: boolean) => set({ darkMode: enabled }),
      setSimulationDuration: (minutes: number) =>
        set({
          simulationDuration: minutes,
        }),
      setSimulationQuestionsCount: (count: number) =>
        set({
          simulationQuestionsCount: count,
        }),
      setNotificationsEnabled: (enabled: boolean) =>
        set({
          notificationsEnabled: enabled,
        }),
      toggleCategory: (category: Category) =>
        set((state) => {
          const isSelected = state.selectedCategories.includes(category);
          return {
            selectedCategories: isSelected
              ? state.selectedCategories.filter((c) => c !== category)
              : [...state.selectedCategories, category],
          };
        }),
      toggleDifficulty: (difficulty: Difficulty) =>
        set((state) => {
          const isSelected = state.selectedDifficulties.includes(difficulty);
          return {
            selectedDifficulties: isSelected
              ? state.selectedDifficulties.filter((d) => d !== difficulty)
              : [...state.selectedDifficulties, difficulty],
          };
        }),
      resetSettings: () => set(initialSettings),
    }),
    {
      name: "interview-prep-settings",
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);
